<template>
  <div class="createPost-container">
    <el-form ref="postForm" :model="postForm" :rules="rules" class="form-container">
      <div class="createPost-main-container">
        <el-row>
          <el-col :span="24">
            <el-form-item style="margin-bottom: 40px;" prop="消息标题">
              <MDinput v-model="postForm.title" :maxlength="100" name="name" required>消息标题</MDinput>
            </el-form-item>

            <div class="postInfo-container">
              <el-row>
                <el-col :span="10">
                  <el-form-item label-width="80px" label="发布对象:" class="postInfo-container-item">
                    <el-select
                      v-model="postForm.userName"
                      :remote-method="getRemoteUserList"
                      filterable
                      default-first-option
                      remote
                      placeholder="搜索对象"
                    >
                      <el-option
                        v-for="(item,index) in userListOptions"
                        :key="item+index"
                        :label="item"
                        :value="item"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>

                <el-col :span="6">
                  <el-form-item label-width="90px" label="级别:" class="postInfo-container-item">
                    <el-select v-model="postForm.grade" placeholder="请选择等级">
                      <el-option label="一级" value="1"></el-option>
                      <el-option label="二级" value="2"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="10">
                  <el-form-item label-width="80px" label="完成时间:" class="postInfo-container-item">
                    <el-date-picker
                      v-model="postForm.overTime"
                      type="datetime"
                      format="yyyy-MM-dd HH:mm:ss"
                      placeholder="请选择完成时间"
                    />
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item label-width="90px" label="类型:" class="postInfo-container-item">
                    <el-radio v-model="postForm.genre" label="1">消息</el-radio>
                    <el-radio v-model="postForm.genre" label="2">任务</el-radio>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label-width="80px" label="消息内容:">
                    <el-input
                      type="textarea"
                      maxlength="500"
                      show-word-limit
                      :rows="5"
                      placeholder="请输入消息内容"
                      v-model="postForm.messCount"
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col width="100%">
                  <el-form-item label-width="80px" label="备注:" width="100%">
                    <el-input
                      type="textarea"
                      :rows="4"
                      maxlength="300"
                      show-word-limit
                      placeholder="请输入备注"
                      v-model="postForm.messageRemark"
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item style="text-align: center;">
                    <el-button type="primary"  @click="submitForm">新增</el-button>
                    <el-button>取消</el-button>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-form>
  </div>
</template>

<script>
import MDinput from '@/components/MDinput'
import { validURL } from '@/utils/validate'
import { fetchMessage } from '@/api/message'
import { searchUser } from '@/api/remote-search'

const defaultForm = {
  status: 'draft',
  // title: '', // 文章题目
  // content: '', // 文章内容
  // content_short: '', // 文章摘要
  // source_uri: '', // 文章外链
  // image_uri: '', // 文章图片
  // display_time: undefined, // 前台展示时间
  id: undefined
  // platforms: ['a-platform'],
  //comment_disabled: false,
  // importance: 0
}

export default {
  name: 'MessageDetail',
  components: {
    MDinput
  },
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    const validateRequire = (rule, value, callback) => {
      if (value === '') {
        this.$message({
          message: rule.field + '为必传项',
          type: 'error'
        })
        callback(new Error(rule.field + '为必传项'))
      } else {
        callback()
      }
    }
   
    const addMessage = { 

      genre: '', //任务或者消息单选
      grade: '', //等级
      messCount: '', //消息内容
      messageRemark: '', //消息备注
      title: '', //消息标题
      userName: '' ,//发布对象
      overTime:'',//完成时间
    }
    return {
      postForm: Object.assign({}, addMessage),
      loading: false,
      userListOptions: [],
      rules: {
        messageRemark: [{ validator: validateRequire }],
        title: [{ validator: validateRequire }],
        messCount: [{ validator: validateRequire }],
      },
      tempRoute: {},
      
    }
  },
  computed: {
    contentShortLength() {
      return this.postForm.content_short.length
    },
    displayTime: {
      //完成时间
      get() {
        return +new Date(this.postForm.display_time)
      },
      set(val) {
        this.postForm.display_time = new Date(val)
      }
    }
  },
  created() {
    if (this.isEdit) {
      const id = this.$route.params && this.$route.params.id
      this.fetchData(id)
    }
    this.tempRoute = Object.assign({}, this.$route)
  },
  methods: {
    fetchData(id) {
      fetchMessage(id)
        .then((response) => {
          this.postForm = response.data
          // console.log("wowo"+response.data)

          // just for test
          //this.postForm.title += `   Article Id:${this.postForm.id}`
          this.postForm.content_short += `   Article Id:${this.postForm.id}`

          // set tagsview title
          this.setTagsViewTitle()

          // set page title
          this.setPageTitle()
        })
        .catch((err) => {
          console.log(err)
        })
    },
    setTagsViewTitle() {
      const title = '编辑'
      const route = Object.assign({}, this.tempRoute, {
        title: `${title}-${this.postForm.id}`
      })
      this.$store.dispatch('tagsView/updateVisitedView', route)
    },
    setPageTitle() {
      const title = '编辑'
      document.title = `${title} - ${this.postForm.id}`
    },
    submitForm() {
      console.log(this.postForm)
      this.$refs.postForm.validate((valid) => {
        if (valid) {
          this.loading = true
          this.$notify({
            title: '成功',
            message: '发布成功',
            type: 'success',
            duration: 2000
          })
          this.postForm.status = 'published'
          this.loading = false
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    draftForm() {
      if (
        this.postForm.content.length === 0 ||
        this.postForm.title.length === 0
      ) {
        this.$message({
          message: '请填写必要的标题和内容',
          type: 'warning'
        })
        return
      }
      this.$message({
        message: '保存成功',
        type: 'success',
        showClose: true,
        duration: 1000
      })
      this.postForm.status = 'draft'
    },
    getRemoteUserList(query) {
      searchUser(query).then((response) => {
        if (!response.data.items) return
        this.userListOptions = response.data.items.map((v) => v.name)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import '~@/styles/mixin.scss';

.createPost-container {
  position: relative;

  .createPost-main-container {
    padding: 5px 45px 20px 50px;

    .postInfo-container {
      position: relative;
      @include clearfix;
      margin-bottom: 10px;

      .postInfo-container-item {
        float: left;
      }
    }
  }

  .word-counter {
    width: 40px;
    position: absolute;
    right: 10px;
    top: 0px;
  }
}

.article-textarea /deep/ {
  textarea {
    padding-right: 40px;
    resize: none;
    border: none;
    border-radius: 0px;
    border-bottom: 1px solid #bfcbd9;
  }
}
</style>
